package com.ly.hotel.view.common;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.ly.hotel.R;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyKeyEventCode;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.msgevent.CloseActivityEvent;
import com.ly.hotel.msgevent.NetworkEvent;
import com.ly.hotel.spainterface.jg.ActivityCollector;
import com.ly.hotel.util.DensityUtil;
import com.ly.hotel.util.TipsUtil;
import com.ly.hotel.util.TouchUtil;
import com.ly.hotel.view.liuwei.InputHandNoActivity;

import de.greenrobot.event.EventBus;

public class BaseActivity extends Activity {

	protected MyApplication app;
	protected boolean hidenKeyInput = false;// 不响应遥控器输入
	private int START_SETTING = 1;
	public String className = "未知类";
	private ThisHandler handlerMsg = new ThisHandler(this);
	public Context mcontext;
	public int lastKeyCode;
	public Timer b_timer;
	public boolean isHidenKeyInput() {
		return hidenKeyInput;
	}

	public void setHidenKeyInput(boolean enable) {
		this.hidenKeyInput = enable;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActivityCollector.addActivity(this);
		className = getClass().getSimpleName();
		Log.i("BaseActivity", className + "->onCreate");
		app = (MyApplication) getApplication();
		mcontext = getBaseContext();
		EventBus.getDefault().register(this);
		checkBg();
	}

	public void waitInitFinsh(int times) {
		b_timer = new Timer(true);
		setHidenKeyInput(true);
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				setHidenKeyInput(false);
				b_timer.cancel();
			};
		};

		b_timer.schedule(task, times);
	}
	@Override
	protected void onStart() {
		super.onStart();
		Log.i("BaseActivity", className + "->onStart");
	}

	@Override
	protected void onPause() {
		Log.i("BaseActivity", className + "->onPause");
		super.onPause();
	}

	@Override
	protected void onResume() {
		Log.i("BaseActivity", className + "->onResume");
		handlerMsg.post(new Runnable() {
			
			@Override
			public void run() {
				if(className != null){
					String content=null;
					content = MyLogsManager.fixClassName(className);
					if(content != null){
						EventBus.getDefault().post(new SendLogEvent("ACTION" + "\t" + content));
					}
				}				
			}
		});
		super.onResume();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		Log.i("BaseActivity", className + "->onDestroy");
		super.onDestroy();
		EventBus.getDefault().unregister(this);
		ActivityCollector.removeActivity(this);
	}

	private void checkBg(){
		if (MyApplication.getSeatBitmap() != null) {
			this.getWindow().setBackgroundDrawable(new BitmapDrawable(getResources(),MyApplication.getSeatBitmap()));
		} else {
			File f = new File(Constants.SEAT_FILE_PATH);
			if (f.exists()) {
				Bitmap bgImage = BitmapFactory.decodeFile(Constants.SEAT_FILE_PATH);
				if (bgImage != null) {
					this.getWindow().setBackgroundDrawable(new BitmapDrawable(getResources(),bgImage));
					MyApplication.setSeatBitmap(bgImage);
				}
			}
		}
	}

	/**
	 * 监听网络状态变化
	 * 
	 * @param e
	 */
	public void onEventMainThread(NetworkEvent e) {
		synchronized (this) {
			Log.i("BaseActivity", "网络状态变化................." + e.isOk());
			if (!e.isOk()) {
				TipsUtil.networkUnable(this);
			}
		}
	}

	public void onEventMainThread(CloseActivityEvent e) {
		this.finish();
	}

	// 解决Android中多次点击启动多个相同界面的问题
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			if (TouchUtil.isFastDoubleClick()) {
				Log.i("BaseActivity", "忽略重复的点击");
				return true;
			}
		}
		return super.dispatchTouchEvent(ev);
	}

	private boolean waitSetting = false;

	@Override
	public boolean onKeyDown(final int keyCode, KeyEvent event) {

		if (isHidenKeyInput()) {
			if (keyCode == MyKeyEventCode.KEYCODE_SET) {
				waitSetting = false;
				waitInitFinsh(1000);// 避免按住不放直接进入设置界面
			} else {
				Log.i(className, "屏蔽按键处理");
			}
			return true;
		}
		lastKeyCode = keyCode;

		// 会触发电视和电影全屏退出的，增加退出确定窗口
		if ((keyCode == KeyEvent.KEYCODE_BACK) && event.getRepeatCount() == 0) {

			Log.i("BaseActivity",className + " " + keyCode);
			// 下面这些是全屏界面需要做退出确认的
			if (className != null && ((className.equals("com.ly.hotel.view.live.TvActivity1"))
					|| (className.equals("com.ly.hotel.view.fragments.vod.NativeVideoPlayerActivity"))
					)) {

				CustomDialog.Builder builder = new CustomDialog.Builder(this);
				builder.setTitle(getString(R.string.exit_tips));
				builder.setFirstButton(getString(R.string.yes), new OnClickListener() {
					@Override
					public void onClick(DialogInterface di, int arg1) {
						switch (keyCode) {
						case KeyEvent.KEYCODE_BACK:// 退出
							// finish();
							// 全屏退出都要把之前的activity销毁的，统一在这个switch外面调用finish()
							break;

						}
						di.dismiss();
						finish();
					}
				});
				builder.setSecondButton(getString(R.string.no), new OnClickListener() {
					@Override
					public void onClick(DialogInterface di, int arg1) {
						di.dismiss();
					}
				});
				builder.create().show();
//				lastKeyCode = keyCode;
				return true;
			}
		}
 
		if(keyCode == KeyEvent.KEYCODE_0){
			if (waitSetting == true) {
				handlerMsg.removeMessages(START_SETTING);
				waitSetting = false;
			}
		} else {
			switch(MyKeyEventCode.getAction(keyCode)){
				/*case MyKeyEventCode.ACTION_MYHOME:
					Intent intent = new Intent(this, TabHostActivity.class);
					startActivity(intent);
					finish();
					return true;*/
				case MyKeyEventCode.ACTION_CALL:// 呼叫
					if(app.isBtnItemEnable("呼叫")){
						if(event.getRepeatCount() == 0){
							call();
						}
					}
					break;
					
				case MyKeyEventCode.ACTION_LIUWEI:// 留位
					if (MyApplication.myLicenseGetValue("留位").equals(1)) {
						liuwei(this);
					}
					break;
					
				case MyKeyEventCode.ACTION_SET:// 操作指南
					if (!waitSetting) {
						Message msg = new Message();
						msg.what = START_SETTING;
						handlerMsg.sendMessageDelayed(msg, 2000);
						waitSetting = true;
					}
					break;

				default:
					break;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	public static void liuwei(Context context) {
		InputHandNoActivity dialog = new InputHandNoActivity(context, R.style.InputDialog);// 创建Dialog并设置样式主题
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
		EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_LIUWEI_WAIT));
	}

	public void call() {
		
		String callTips="";
		if(app.getCallStatus() == Constants.CALL_CANCLE){
			callTips = getString(R.string.call_warning_sure);
		}else if(app.getCallStatus() == Constants.CALL_REQUEST){
			callTips = getString(R.string.call_warning_cancle);
		}
		
		CustomDialog.Builder builder = new CustomDialog.Builder(getBaseContext()).setTitle(callTips)
				.setFirstButton(getString(R.string.yes), new OnClickListener() {

					@Override
					public void onClick(DialogInterface di, int arg1) {
						
							new Thread(new Runnable() {
								@Override
								public void run() {
									String rv = "";
									rv = app.changeLight();
									Message msg = new Message();
									Bundle data = new Bundle();
									data.putString("msg", rv);
									msg.setData(data);
									msg.what = 4;
									handlerMsg.sendMessage(msg);
								}

							}).start();
							
							if(app.getCallStatus() == Constants.CALL_CANCLE){
								EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_CALL_PREFIX + "呼叫"));
							}else{
								EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_CALL_PREFIX + "取消呼叫"));
							}
							
							di.dismiss();
					}
				}).setSecondButton(getString(R.string.no), new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface di, int arg1) {
						di.dismiss();
					}
				});

		CustomDialog ad = builder.create();
		ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		ad.show();
		ad.getWindow().setLayout(DensityUtil.dip2px(300), DensityUtil.dip2px(200));
	}

	private static class ThisHandler extends Handler {
		private WeakReference<BaseActivity> wrActivity;

		public ThisHandler(BaseActivity activity) {
			wrActivity = new WeakReference<BaseActivity>(activity);
		}

		@Override
		public void handleMessage(Message message) {
			BaseActivity act = wrActivity.get();
			if (act != null) {
				switch (message.what) {
				case 1:
					if (act.className != null && (!(act.className.equals("com.ly.hotel.view.live.TvActivity"))
							|| (act.className.equals("com.ly.hotel.view.vod.VideoPlayerActivity"))
							|| (act.className.equals("com.ly.hotel.view.vod.NativeVideoPlayerActivity")))){
						Intent intent = new Intent(Intent.ACTION_MAIN);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.setClassName("com.ly.hotel", "com.ly.hotel.view.setting.UserGuideActivity");
	
						act.startActivity(intent);
					}
					act.waitSetting = false;

					break;

				case 4:
					String jsonStr = message.getData().getString("msg");
					if(jsonStr != null && !jsonStr.equals("")){
						Toast.makeText(act.getBaseContext(), jsonStr, Toast.LENGTH_SHORT).show();
					}
				}
			}
		}
	}

}
